package com.edu.neusoft.furniture_sale.controller;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import com.edu.neusoft.furniture_sale.common.ResponseResult;
import com.edu.neusoft.furniture_sale.common.enums.AppHttpCodeEnum;
import com.edu.neusoft.furniture_sale.dto.UserDto;
import com.edu.neusoft.furniture_sale.entity.User;
import com.edu.neusoft.furniture_sale.service.UserService;
import com.edu.neusoft.furniture_sale.utils.ValidateCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * 员工信息(User)表控制层
 *
 * @author makejava
 * @since 2024-12-09 23:36:25
 */
@RestController //返回JSON类型的数据
@Slf4j  //lombok提供的打印功能
@Api(value = "app端用户登录",tags = "app端用户登录")
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录接口
     * @param userDto
     * @return
     */
    @ApiOperation("登录")
    @PostMapping("/login")
    public ResponseResult login(@RequestBody UserDto userDto, HttpSession session){
        return userService.login(userDto, session);
    }

    /**
     * 登出接口
     * @param session
     * @return
     */
    @ApiOperation("登出")
    @PostMapping("/logout")
    public ResponseResult loginOut(HttpSession session){
        session.removeAttribute("loginUser");
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 展示个人信息接口
     * @param session
     * @return
     */
    @ApiOperation("展示个人信息")
    @GetMapping("/show")
    public ResponseResult show(HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        log.info(String.valueOf(user.getId()));
        return ResponseResult.okResult(userService.getById(user.getId()));
    }

    /**
     * 发送手机短信验证码
     * @param dto
     * @return
     */
    @PostMapping("/发送验证码")
    public ResponseResult sendMsg(@RequestBody UserDto dto, HttpSession session){
        //获取用户名
        String phone = dto.getPhone();

        if (StringUtils.isNotEmpty(phone)) {
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}", code);

            //需要将生成的验证码保存到session
            session.setAttribute(phone, code);


            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.ERROR, "短信发送失败");
    }

}

